<template>
	<a-modal v-bind="options" class="child-renewal">
		<template #title>
			<div>选择续租子合同</div>
			<div id="dialog_header_search">
				<search-input v-model:params="params" v-bind="searchOption" />
			</div>
		</template>

		<div class="flex-container-nomal" style="height: 70vh">
			<vxe-grid ref="grid" v-bind="gridOptions">
				<template #label="{row}">
					<a-tag :color="labelStatus[row.label].color" style="min-width: 70px">
						{{ labelStatus[row.label].name }}
					</a-tag>
					<template v-if="row.label != 41 && APPROVAL_STATUS_MAP[row.approvalStatus]">
						<a-tooltip destroy-tooltip-on-hide>
							<template #title>
								{{ APPROVAL_STATUS_MAP[row.approvalStatus].label }}
							</template>
							<svg-icon :icon-class="APPROVAL_STATUS_MAP[row.approvalStatus].icon" />
						</a-tooltip>
					</template>
				</template>
				<template #contract="{row}">
					<a-tooltip placement="bottom">
						<template #title>{{ row.contractMedium === 1 ? '纸质合同' : '电子合同' }}</template>
						<a-avatar v-if="row.contractMedium === 1" :size="20" class="contarct-type-circle">纸</a-avatar>
						<a-avatar v-else :size="20" class="contarct-type-circle contarct-online">电</a-avatar>
					</a-tooltip>
					{{ SIGN_TYPE_MAP[row.signType] }} / {{ desensitizationName(row.signEmpName) }} / {{ formatDate(row.signTime) }}
					<br />
					<a-tag class="border-none" color="processing">{{ row.houseAlias }}</a-tag>
					{{ row.houseAddress }}
				</template>
				<template #contractType="{row}">
					<template v-if="row.contractType === 1">个人合同</template>
					<template v-if="row.contractType === 2">
						企业合同{{ row.signType === 5 ? '-补签合同' : row.signType === 4 ? '-换房合同' : '' }}
						<br />
						{{ row.enterPriseName }}
					</template>
					<template v-if="row.contractType === 4">企业合同-框架协议</template>
				</template>
				<template #personal="{row}">
					{{ desensitizationName(row.name) }} / {{ desensitizationPhone(row.phone) }}
					<br />
					{{ 2 === row.contractType ? '社会信用代码' : CERTIFICATION_TYPE_MAP[row.certificationType] }} / {{ row.identityCard }}
				</template>
				<template #cycle="{row}">
					{{ formatDate(row.beginTime) }} 至 {{ formatDate(row.endTime) }}
					<br />
					{{ row.price }}元/月
					<span>押金{{ row.deposit }}元</span>
					/
					<span>押{{ row.depositMonth }}</span>
					<span v-if="row.periodMonth === 99">一次性付</span>
					<span v-else>付{{ row.periodMonth }}</span>
				</template>

				<template #action="{row}">
					<a v-if="!props.hideDetails" @click="handlerClick(row, 0)">查看合同</a>
				</template>
			</vxe-grid>
		</div>

		<template #footer>
			<a-row type="fixed" justify="end">
				<a-space :size="12">
					<a-button @click="options.onCancel">取消</a-button>
					<a-button type="primary" @click="confirm" :disabled="selections.length === 0">确定</a-button>
				</a-space>
			</a-row>
		</template>
	</a-modal>

	<!-- 详情弹窗 -->
	<detail-dialog
		v-if="!props.hideDetails"
		:contract-id="records.contractId"
		:data="records"
		:enterPriseContractId="records.enterPriseContractId as string"
		v-model:visible="visibles.showDetails"
		:enterpriseSignType="records.enterpriseSignType"
		:isApproval="isApproval"
		@close="getListF" />

	<!-- 包租合同 续租 -->
	<signing-dialog
		v-model:visible="visibles.addCharter"
		:signing-type="'charter'"
		@success="success"
		:approvalStatus="visibles.approvalStatus"
		:reletId="reletId as string"
		:reletIds="reletIds" />
</template>

<script setup lang="ts">
	import {onMounted, reactive, ref, toRef, watch} from 'vue'
	import {VxeGridInstance, VxeGridProps} from 'vxe-table'
	import {DownOutlined, ExclamationCircleFilled} from '@ant-design/icons-vue'
	import {APPROVAL_STATUS_MAP, SIGN_TYPE_MAP} from '@/interface/contract'
	// import {labelStatus} from '@/utils/charter-contract'
	import {labelStatus, statusList, charterStatusList} from '@/utils/tenant-status'
	import {CERTIFICATION_TYPE_MAP} from 'yuxin-base/src/constant/index'
	import {formatDate} from 'yuxin-base/src/utils/date'
	import {pagerConfig, proxyConfigProps} from 'yuxin-base/src/utils/vxe-table'
	import {getPageByEnterprise} from '@/api/charter-contract'
	import {enterpriseDetails} from '@/api/enterprise-library'
	import {desensitizationName, desensitizationPhone} from 'yuxin-base/src/utils/desensitization'
	import SigningDialog from '@/components/contract/signing/signing-dialog.vue'
	import XEUtils from 'xe-utils'
	import dayjs, {Dayjs} from 'dayjs'
	import {Modal, message} from 'ant-design-vue'
	import {useStore} from '@/store/index'
	import {FormItemRest} from 'ant-design-vue/es/form'
	import {hasApproval} from '@/api/charter-contract'
	import {SearchProps} from 'yuxin-base/src/types'
	import DetailDialog from '@/components/contract/contract-detail-dialog/index.vue'

	const props = withDefaults(
		defineProps<{
			visible: boolean
			id?: string
			enterContractEndDate?: string | null
			cooperationEndDate?: string | null
			hideDetails?: boolean
			searchContainer?: string | boolean
			isApproval?: boolean
		}>(),
		{
			searchContainer: '#dialog_header_search',
			isApproval: false
		}
	)

	const emit = defineEmits(['update:visible', 'success'])

	// 弹窗配置
	const options = reactive({
		width: '80vw',
		// title: '选择续租子合同',
		maskClosable: false,
		centered: true,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		bodyStyle: {padding: '10px'},
		onCancel: () => {
			emit('success')
			emit('update:visible', false)
		}
	})

	// 搜索配置
	const searchOption = reactive<SearchProps>({
		placeholder: '房源地址',
		onSearch() {
			getListF(1)
		}
	})

	const grid = ref<VxeGridInstance>()

	/**
	 * 合同数据
	 */
	const records = ref<any>({})
	const visibles = reactive<any>({
		teleport: false,
		showDetails: false,
		addCharter: false,
		approvalStatus: ''
	})

	const reletId = ref<any>(null)
	const reletIds = ref<any>([])

	const params = reactive<any>({
		contractStatus: 2,
		approvalStatusList: [-1, 3],
		like: null,
		enterContractIds: [],
		enterContractEndDate: null
	})

	/** 选中企业合同 */
	const selections = ref<any>([])

	const gridOptions = reactive<VxeGridProps>({
		height: 'auto',
		showOverflow: true,
		rowConfig: {
			height: 60,
			isHover: true,
			keyField: 'id'
		},
		checkboxConfig: {
			reserve: true
		},
		// @ts-ignore
		onCheckboxAll({records}: any) {
			selections.value = records
		},
		onCheckboxChange({records}: any) {
			selections.value = records
		},
		columns: [
			{
				type: 'checkbox',
				width: 60
			},
			{
				title: '状态',
				width: 120,
				slots: {
					default: 'label'
				}
			},
			{
				minWidth: 400,
				resizable: true,
				title: '签约类型/成交方式/签约人/签约日期/房源编号/房源地址',
				slots: {
					default: 'contract'
				}
			},
			{
				minWidth: 200,
				title: '合同类型',
				resizable: true,
				slots: {
					default: 'contractType'
				}
			},
			{
				minWidth: 260,
				resizable: true,
				visible: !params.backRentRemind,
				title: '周期/租金/押金/付款方式',
				slots: {
					default: 'cycle'
				}
			},
			{
				title: '操作',
				width: 150,
				align: 'center',
				fixed: 'right',
				slots: {
					default: 'action'
				}
			}
		],
		pagerConfig,
		proxyConfig: {
			props: proxyConfigProps,
			ajax: {
				query({page: {currentPage: current, pageSize: size}}) {
					return queryData({...params, current, size})
				}
			}
		}
	})

	const getListF = (page?: any) => {
		grid.value?.commitProxy(page === 1 ? 'reload' : 'query')
	}

	const queryData = async (params: any) => {
		const res = await getPageByEnterprise({
			...params
		})
		console.log('🚀 ~ file: batch-operate.vue:287 ~ queryData ~ res:', res)
		// if (!res.data || res.data.length === 0) {
		// 	options.onCancel()
		// }
		return res
	}

	//操作
	const handlerClick = async (row: any, field: number) => {
		records.value = XEUtils.clone(row, true)
		visibles.approvalStatus = row.approvalStatus
		reletId.value = null

		switch (field) {
			case 0:
				visibles.showDetails = true

				break
		}
	}

	const confirm = async () => {
		const checkeds = grid.value?.getCheckboxRecords().concat(grid.value.getCheckboxReserveRecords()) || []
		console.log('🚀 ~ file: child-renewal.vue:291 ~ confirm ~ checkeds:', checkeds)
		console.log(props?.cooperationEndDate, 'props?.enterContractEndDate')
		try {
			checkeds.forEach((row, index) => {
				if (dayjs(props?.cooperationEndDate).diff(row.endTime, 'day') == 0) {
					message.warning(
						`无法续租,当前选中的第${
							index + 1
						}个合同周期结束日期等于合作周期结束日期,如需续租,请先至【企业库】延长与承租企业合作周期`
					)
					throw new Error()
				}
			})
		} catch (e) {
			return
		}

		reletId.value = props.id
		reletIds.value = checkeds.map(item => {
			return {
				houseId: item.houseId,
				enterPriseContractId: item.enterPriseContractId
			}
		})
		console.log('🚀 ~ file: child-renewal.vue:310 ~ confirm ~ reletIds.value:', reletIds.value)
		visibles.addCharter = true
	}

	const close = () => {
		visibles.showDetails = false
		getListF()
	}

	const success = (type = 1) => {
		if (type === 2) {
			getListF
			return
		}

		options.onCancel()
	}

	watch(
		() => props.visible,
		(newVal: boolean) => {
			if (newVal) {
				params.enterContractIds = [props.id]
				params.enterContractEndDate = props.enterContractEndDate
				// grid.value?.refreshColumn()
			}
		}
	)

	onMounted(() => {})
</script>

<style lang="less">
	.child-renewal {
		overflow: hidden;

		.ant-modal-header {
			height: 55px;
			padding: 11px 24px;

			& > .ant-modal-title {
				line-height: 31px;
				display: flex;
				align-items: center;
				justify-content: space-between;

				#dialog_header_search {
					min-width: 600px;
					margin-right: 30px;
					font-weight: normal;
				}
			}
		}
	}
</style>
